<template>
  <div class="examPage">
    <div class="chat_box" id="chatBox" :style="{
      'height': smartStep == 2 ? 'calc(100vh - 80px)' : 'calc(100vh - 260px)',
    }">
      <template v-for="(item, index) in messageList">
        <!-- 医生 -->
        <template v-if="item.from == 'doctor'">
          <!-- 文本 -->
          <template v-if="item.type == 'TEXT'">
            <div class="chat_li">
              <div class="chat_li_left">
                <div class="user">
                  <img src="@/assets/img/img_male.png" alt="" />
                </div>
                <div class="bubble">
                  {{ item.msg }}
                </div>
              </div>
            </div>
          </template>
          <!-- 卡片 -->
          <template v-if="item.type == 'CARD'">
            <div class="chat_tit">
              推荐科室
            </div>
            <div class="chat_tip">
              智能导诊结果仅供参考，具体挂号科室请以实际为准
            </div>
            <div class="chat_li">
              <div class="chat_li_left" style="flex-flow: column;">
                <!-- <div class="user">
                  <img src="@/assets/img/img_male.png" alt="" />
                </div> -->
                <div class="card" v-for="value in item.msg">
                  <template >
                    <div class="card_1"><span></span>{{ value.major }}</div>
                    <div class="card_3">{{ value.majorDesc }}</div>
                    <div class="card_2">
                      <div class="card_2_cell" v-for="v in value.deptList">
                        <div class="name">{{ v.deptName }}</div>
                        <div class="btn" @click.stop="goREG(v)">挂号</div>
                      </div>
                    </div>
                  </template>

                </div>
              </div>
            </div>
          </template>
        </template>
        <!-- 患者 -->
        <template v-if="item.from == 'patient'">
          <!-- 文本 -->
          <template v-if="item.type == 'TEXT'">
            <div class="chat_li">
              <div class="chat_li_right">
                <div class="bubble">{{ item.msg }}</div>
                <div class="user">
                  <img src="@/assets/img/icon_boy.png" alt="" />
                </div>
              </div>
            </div>
          </template>
        </template>
      </template>
    </div>
    <div class="smart_box" v-if="smartStep != 2 && smartStep != 0">
      <div class="smart_box_top">
        <template v-if="smartStep == 0">
          <!-- <picker :data="sexageData" v-model="sexageValue" @on-change="change"></picker> -->
          <div class="smart_box_top2">

          </div>
        </template>
        <template v-if="smartStep == 1">
          <div class="smart_box_top1">
            <div v-for="(item, index) in list1" :class="{ 'smartActive': selectIdex == item.id }"
              @click="selectFun(item)">
              {{ item.name }}
            </div>

          </div>
        </template>
        <!-- <template v-if="smartStep == 2">
          <div class="smart_box_top1">
            <div v-for="(item, index) in list2" :class="{ 'smartActive': item.checked == true }"
              @click="checkedFun(item, index)">
              {{ item.name }}
            </div>
          </div>
        </template> -->
      </div>

      <div class="btn_box" v-show="smartStep != 0">
        <div class="btn_box_1" @click="stepBack">上一步</div>
        <!-- <div class="btn_box_2" @click="stepNext">确定</div> -->
      </div>
    </div>
    <div class="btn_box0" v-show="smartStep == 0">
      <div class="btn_box0_2" @click="stepStart(item)" v-for="item in ageList">
        {{ item.name }}
      </div>
      <!-- <div class="btn_box0_1" @click="stepStart(1)">
        16岁以上
      </div> -->

    </div>
    <div class="btn_box0" v-show="smartStep == 2">
      <div class="btn_box0_1" @click="reset">
        重新答题
      </div>
    </div>
  </div>
</template>
<script>
import { submitAnswer, guideList } from "@/api/api";
import { Picker } from "vux";
import { getToken,removeWxUserinfoCookies,removeToken} from "@/api/auth";
export default {
  components: {
    Picker,

  },
  data() {
    return {
      smartStep: 0,
      sexageValue: [],
      ageList: [],
      age: [],
      currentAge: 0,
      sexageData: [["男", "女"]],
      list1: [],
      list2: [],
      selectIdex: null,
      selectItem: {},
      checkedIdx: null,
      messageList: [
        {
          from: "doctor",
          type: "TEXT",
          msg: "您好，我是AI导诊助手，可以根据您的症状描述为您推荐可挂号的科室或医生",
        },
        {
          from: "doctor",
          type: "TEXT",
          msg: "请问您年龄是？",
        },
      ],
    };
  },
  created() {
    // this.agefun();
    this.init()

  },
  mounted() {
    var chatDiv = document.getElementById("chatBox")
    // console.log(chatDiv.scrollHeight,chatDiv.scrollTop)
    chatDiv.scrollTop = chatDiv.scrollHeight;
  },
  methods: {
    init() {
      this.guideList();
      if (window.localStorage.getItem("smartStep")) {
        this.smartStep = parseInt(window.localStorage.getItem("smartStep"))
      }
      if (window.localStorage.getItem("messageList")) {
        this.messageList = JSON.parse(window.localStorage.getItem("messageList"))
      }
      if (window.localStorage.getItem("guideList")) {
        this.list1 = JSON.parse(window.localStorage.getItem("guideList"))
      }

    },
    guideList(ids) {
      var data = {
        parentId: "0", //0 : 所有一级症状
        selectAll: "0" //查询全部子集
      };
      guideList(data).then((res) => {
        if (res.code == 200) {
          this.ageList = res.data
        }
      });
    },
    submitAnswer(names) {
      var data = {
        ids: names.toString(),
        age: this.currentAge,
      };
      submitAnswer(data).then((res) => {
        if (res.code == 200) {
          if (res.data.length > 0) {
            this.messageList.push({
              from: "doctor",
              type: "CARD",
              msg: res.data,
            });
          } else {
            this.messageList.push({
              from: "doctor",
              type: "TEXT",
              msg: "没有找到符合您症状的科室",
            });
          }
        }
      });
    },

    selectFun(item) {
      this.selectIdex = item.id;
      this.selectItem = item;
      if (item.isOther == 1) {
        window.localStorage.setItem("smartStep", JSON.stringify(this.smartStep))
        window.localStorage.setItem("messageList", JSON.stringify(this.messageList))
        this.$router.push({
          path: "/smart_leading_examining_search",
          query: item
        })
      } else {
        this.messageList.push({
          from: "patient",
          type: "TEXT",
          msg: this.selectItem.name,
        });
        if (item.isAnswer == 1) {
          this.messageList.push({
            from: "doctor",
            type: "CARD",
            msg: item.majorList,
          });

        } else {
          guideList({
            parentId: item.id, //0 : 所有一级症状
            selectAll: item.isOther //查询全部子集
          }).then((res) => {
            if (res.code == 200) {
              if (res.data.length > 0) {
                this.messageList.push({
                  from: "doctor",
                  type: "CARD",
                  msg: res.data,
                });
              } else {
                this.messageList.push({
                  from: "doctor",
                  type: "TEXT",
                  msg: "没有找到符合您症状的科室",
                });
              }

            }
          });

        }
        this.smartStep += 1

      }
    },
    checkedFun(item, index) {
      this.list2[index].checked = !this.list2[index].checked;
      var arr = [];
      this.list2.forEach((element) => {
        if (element.checked == true) {
          arr.push(element);
        }
      });
      this.checkedIdx = arr;
    },
    stepBack() {
      if (this.smartStep > 0) {
        this.smartStep--
        this.messageList.pop()
        this.messageList.pop()
      }
    },
    stepStart(item) {
      if (this.smartStep == 0) {
        this.messageList.push({
          from: "patient",
          type: "TEXT",
          msg: item.name,
        });

        this.messageList.push({
          from: "doctor",
          type: "TEXT",
          msg: "请问您此次就医的目的是？",
        });
        guideList({
          parentId: item.id, //0 : 所有一级症状
          selectAll: item.isOther //查询全部子集
        }).then((res) => {
          if (res.code == 200) {
            this.list1 = res.data
            window.localStorage.setItem("guideList", JSON.stringify(this.list1))
          }
        });
        this.smartStep += 1;
      }
    },
    stepNext() {

      if (this.smartStep == 1) {
        if (this.selectIdex == null) {
          alert("请选择您的疾病部位");
          return;
        }
        this.messageList.push({
          from: "patient",
          type: "TEXT",
          msg: this.selectItem.name,
        });
        this.messageList.push({
          from: "doctor",
          type: "TEXT",
          msg: "请问您的疾病症状？",
        });

        this.guideList(this.selectIdex);
      }
      if (this.smartStep == 2) {
        if (this.checkedIdx == null) {
          alert("请选择您的疾病症状");
          return;
        }
        var msg = "",
          names = [];
        this.checkedIdx.forEach((element, index) => {
          names.push(element.name);
          if (this.checkedIdx.length - 1 == index) {
            msg += element.name;
          } else {
            msg += element.name + ",";
          }
        });
        console.log(names);
        console.log(msg);
        this.messageList.push({
          from: "patient",
          type: "TEXT",
          msg: msg,
        });
        this.submitAnswer(names);
      }
      this.smartStep += 1;
    },
    async goREG(v) {
      console.log(v);
      const that = this;
      var or = await that.isLoginAndIsband();
      if (or) {
        that.$router.push({
          path: "/appointment_next",
          query: {
            deptName: v.deptName,
            deptId: v.deptId,
          },
        });
        window.localStorage.setItem("smartStep", JSON.stringify(this.smartStep))
        window.localStorage.setItem("messageList", JSON.stringify(this.messageList))
      }
    },
    reset() {
      this.smartStep = 0
      this.messageList = [
        {
          from: "doctor",
          type: "TEXT",
          msg: "您好，我是AI导诊助手，可以根据您的症状描述为您推荐可挂号的科室或医生",
        },
        {
          from: "doctor",
          type: "TEXT",
          msg: "请问您年龄是？",
        },
      ]
      window.localStorage.removeItem("messageList")
      window.localStorage.removeItem("smartStep")
      window.localStorage.removeItem("guideList")
    },
    clearFun(){
      try {
        console.log("清理localStorage");
        localStorage.clear();
      } catch (err) {
        console.log("清理localStorage失败:" + err);
      }
      try {
        console.log("清理token");
        removeToken();
        // removeWxUserinfoCookies();
      } catch (err) {
        alert(err)
        console.log(err);
      }
    },
    isLoginAndIsband() {
      const that = this;
      if (!getToken()) {
        that.$vux.confirm.show({
          // 组件除show外的属性
          content: "未登录,请先登录账号",
          onCancel() { },
          onConfirm() {
            that.clearFun()
            that.$router.push({ path: "/" });
          },
        });
        return false;
      } else {
        if (window.localStorage.getItem("isband") == "false") {
          this.$vux.confirm.show({
            // 组件除show外的属性
            content: "请添加就诊人",
            onCancel() { },
            onConfirm() {
              that.$router.push({ path: "/my_patient" });
            },
          });
          return false;
        } else {
          return true;
        }
      }
    },
    agefun() {
      for (var i = 1; i <= 100; i++) {
        this.age.push(i + "岁");
      }
      this.sexageData.push(this.age);
    },
    change(value) {
      console.log("new Value", value);
    },
  },
};
</script>
<style scoped>
.examPage {
  height: 100vh;
  width: 100%;
  background-color: #f7fafd;
}

.smart_box {
  width: 100%;
  height: 240px;
  position: relative;
  background-color: #fff;
}

.smart_box_top {
  height: calc(100% - 45px);
  width: 100%;
  position: relative;
  z-index: 100;
}

.smart_box_top1 {
  max-height: calc(100% - 40px);
  padding: 20px 16px;
  display: flex;

  flex-flow: row wrap;
  overflow-y: scroll;
}

.smart_box_top1>div {
  padding: 0 13px;
  height: 30px;
  line-height: 30px;
  font-size: 15px;
  background: #f7fafd;
  border-radius: 5px;
  margin: 6px 8px;
}

.smartActive {
  color: #448eff;
  border: 1px solid #448eff;
}

.btn_box0 {
  width: calc(100% - 2rem);
  padding: 0 1rem;
  height: 3.75rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  z-index: 1000;
  position: fixed;
  bottom: 0;
  background: #ffffff;

}

.btn_box0_1 {
  width: calc((100% - 0.75rem) / 1);
  height: 2.5rem;
  background: #F7FAFD;
  border: 1px solid #DFE3E8;
  border-radius: 5px;
  font-size: 15px;
  font-family: PingFang SC;
  font-weight: 500;
  color: #3F4551;
  line-height: 2.5rem;
  text-align: center;
}

.btn_box0_2 {
  width: calc((100% - 0.75rem) / 2);
  height: 2.5rem;
  background: #F7FAFD;
  border: 1px solid #DFE3E8;
  border-radius: 5px;
  font-size: 15px;
  font-family: PingFang SC;
  font-weight: 500;
  color: #3F4551;
  line-height: 2.5rem;
  text-align: center;
}

.btn_box {
  height: 2.8125rem;
  width: 100%;
  display: flex;
  position: fixed;
  bottom: 0;
  background: #ffffff;
  box-shadow: 0px 0px 13px 0px rgba(181, 189, 197, 0.28);
  z-index: 1000;
}

.btn_box>div {
  width: 100%;
  height: 100%;
  line-height: 45px;
  font-size: 18px;
  text-align: center;
  /* font-weight: bold; */
}

.btn_box .btn_box_1 {
  color: #fff;
  background-color: #448eff;

}

.btn_box .btn_box_2 {
  background: linear-gradient(90deg, #448eff 0%, #66a3ff 100%);
  color: #fff;
}

.chat_box {
  width: calc(100% - 2rem);

  padding: 0px 1rem;
  overflow-y: auto;
  overflow-x: hidden;
  background-color: #f7fafd;
  padding-top: 20px;
}

.chat_box .tip {
  color: #f82e24;
  font-size: 0.875rem;
  text-align: center;
  margin-bottom: 1.25rem;
}

.chat_li {
  width: 100%;
  margin-bottom: 1.25rem;
  font-size: 0.9375rem;
}

.chat_tip {
  font-size: 13px;
  /* text-align: center; */
  font-weight: 500;
  color: #f72d23;
  line-height: 50px;
}

.chat_tit {
  font-size: 17px;
  font-family: PingFang SC;
  font-weight: 500;
  color: #131A2A;
  line-height: 42px;
}

.chat_li_left {
  display: flex;
  
}

.chat_li_right {
  display: flex;
  justify-content: flex-end;
}

.chat_li_left .user {
  width: 2.5rem;
  height: 2.5rem;
  margin-right: 0.6875rem;
}

.chat_li_right .user {
  width: 2.5rem;
  height: 2.5rem;
  margin-left: 0.6875rem;
}

.chat_li .user>img {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
}

.chat_li_left .bubble {
  max-width: calc(100% - 8.375rem);
  background-color: #ffffff;
  padding: 0.8125rem 1rem;
  border-radius: 0px 0.5rem 0.5rem 0.5rem;
  word-wrap: break-word;
  word-break: break-all;
}

.chat_li_left .card {
  /* width: 100%; */
  padding: 0.625rem 0.8125rem;
  background-color: #fff;
  border-radius: 10px;
  margin-bottom: 12px;
}

.chat_li_left .card .card_1 {

  font-size: 17px;
  font-family: PingFang SC;
  font-weight: bold;
  color: #131A2A;
  line-height: 42px;
  display: flex;
  align-items: center;
}

.chat_li_left .card .card_1 span {
  margin-right: 0.75rem;
  width: 3px;
  height: 15px;
  background: #448EFF;
  border-radius: 2px;

}

.chat_li_left .card .card_3 {
  font-size: 13px;
  font-family: PingFang SC;
  font-weight: 500;
  color: #A4ADBE;
  line-height: 20px;
  margin-bottom: 10px;

}

.chat_li_left .card .card_2 {
  border-radius: 0 0 5px 5px;

  
  border-radius: 6px;
}

.chat_li_left .card .card_2 .card_2_cell {
  background: #F7FAFD;
  margin-bottom: 10px;
  padding: 10px 13px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chat_li_left .card .card_2 .card_2_cell .btn {
  border: 1px solid #448eff;
  border-radius: 4px;
  font-size: 15px;
  color: #448eff;
  height: 25px;
  line-height: 25px;
  width: 45px;
  text-align: center;
}

.chat_li_right .bubble {
  max-width: calc(100% - 8.375rem);
  background-color: #448eff;
  color: #fff;
  padding: 0.8125rem 1rem;
  border-radius: 0.5rem 0rem 0.5rem 0.5rem;
  word-wrap: break-word;
  word-break: break-all;
}
</style>
